import React, { Component } from 'react'
import { Link } from 'react-router-dom'
import './style.scss'
import { func, string, arrayOf, shape, number } from 'prop-types'
import { Carousel } from 'antd-mobile'

class MySwiper extends Component {
  state = {}
  static getDerivedStateFromProps(nextProps, prevState) {
    return prevState.imgHeight ? null : { imgHeight: nextProps.imgHeight }
  }

  render() {
    const { data } = this.props
    const { imgHeight } = this.props
    return (
      <Carousel className="my-swiper-box" autoplay={false} dots={true} infinite>
        {data.map(({ id, path, imgurl, title }) => (
          <Link
            key={id}
            to={path}
            style={{
              display: 'inline-block',
              width: '100%',
              height: imgHeight
            }}
          >
            <img
              src={imgurl}
              title={title}
              style={{
                width: '100%',
                verticalAlign: 'top',
                height: imgHeight
              }}
              onLoad={() => {
                window.dispatchEvent(new Event('resize'))
                this.setState({ imgHeight: 'auto' })
              }}
            />
          </Link>
        ))}
      </Carousel>
    )
  }
}

MySwiper.propTypes = {
  data: arrayOf(
    shape({
      id: number,
      path: string,
      imgurl: string,
      title: string
    })
  ).isRequired,
  imgHeight: number
}

MySwiper.defaultProps = {
  imgHeight: 176
}

export default MySwiper
